package com.veal98.tree;

import com.veal98.bean.TreeNode;

import java.util.Stack;

public class ValidateBinarySearchTree_98 {

    public boolean isValidBST(TreeNode root) {
        if (root == null) {
            return true;
        }

        // 辅助栈
        Stack<TreeNode> stack = new Stack<>();
        // 工作节点
        TreeNode cur = root;
        // 工作节点在中序遍历中的前驱节点
        TreeNode pre = null;

        while (!stack.isEmpty() || cur != null) {
            if (cur != null) {
                stack.push(cur);
                // 左
                cur = cur.left;
            } else {
                // 根
                cur = stack.pop();

                if (pre != null && pre.val >= cur.val) {
                    return false;
                }
                pre = cur;

                // 右
                cur = cur.right;
            }
        }

        return true;
    }

}
